<?php

declare(strict_types=1);

namespace app\api\controller\v1;
use app\common\Frontend;
use app\common\model\Order;
use app\common\model\Product;
use app\common\model\PublicStatus;
use app\common\model\User;
use app\common\model\UserMoneyLog;
use app\common\model\VipDay;
use app\common\model\VipPrice;
use Endroid\QrCode\Writer\PngWriter;
use Endroid\QrCode\Encoding\Encoding;
use Endroid\QrCode\QrCode;
use Exception;
use general\Random;
use think\facade\Config;
use Yansongda\Pay\Pay;
use Yansongda\Pay\Log;

class PaymentCon extends Frontend
{

    protected array $noNeedLogin = ['wxPayment','aliPayment','doPayment','checkPay'];

    protected $model;
    protected $price;
    public function initialize(): void
    {
        parent::initialize();
    }

    //微信支付
    public function wxPayment() : void {
        Pay::config(Config::get("pay"));
        $order = [
            'out_trade_no' => time().'',
            'description' => 'subject-测试',
            'amount' => [
                'total' => 1,
            ],
        ];
        try {
            $result = Pay::wechat()->scan($order);
    
      }catch (\Exception $exception){
        halt($exception);
      }
      halt($result->toArray());
      $qr = $result->code_url;
      $payBase = $this->code($qr);
      halt($payBase);
    }

    //微信支付+支付宝支付集成
    public function doPayment(){
        $order_sn = $this->request->param('order_sn');
        $tab = $this->request->param('tab',PublicStatus::PAY_TYPE_ONE);
        $is_find_order = Order::where(['order_no'=>$order_sn])->find();
        if(!$is_find_order){
            $this->error('创建失败,订单不存在');
        }
        $product = Product::find($is_find_order['product_id']);
        if(!$product){
            $this->error('创建失败,产品不存在');
        }
        Pay::config(Config::get("pay"));
        if(intval($tab) == PublicStatus::PAY_TYPE_ONE){ //微信支付
            $orderData = [
                'out_trade_no' => $order_sn,
                'description' => $product['title'],
                'amount' => [
                //    'total' => intval($is_find_order['pay_price']) * PublicStatus::PUBLIC_ONE_HUNDRED,
                   'total' => intval($is_find_order['pay_price']) ,
        
                ],
            ];
            $result = Pay::wechat()->scan($orderData);
        }else{
            $orderData = [
                'out_trade_no' => $order_sn,
                'total_amount' => intval($is_find_order['pay_price']),
                'subject' => $product['title'],
            ];
            $result = Pay::alipay()->scan($orderData);
        }
        $arr = $result->toArray();
        if(intval($tab) == PublicStatus::PAY_TYPE_TWO && intval($arr['code']) === 10000 && $arr['msg'] == 'Success'){
            $payBase = $this->code($result['qr_code']);
        }else{
            $payBase = $this->code($result['code_url']);
        }
        $this->success('ok',$payBase);
    }


    //支付宝支付
    public function aliPayment() {
        $order_sn = $this->request->param('order_sn');
        $is_find_order = Order::where(['order_no'=>$order_sn])->find();
        if(!$is_find_order){
            $this->error('创建失败,订单不存在');
        }
        Pay::config(Config::get("pay"));
        $result =  Pay::alipay()->scan([
                'out_trade_no' => $order_sn,
                'total_amount' => 0.1,
                'subject' => $is_find_order->remark,
        ]);
        $arr = $result->toArray();
        if(intval($arr['code']) === 10000 && $arr['msg'] == 'Success'){
           $payBase = $this->code($result['qr_code']);
           $this->success('ok',$payBase);
        }
    }
    //转换二维码
    public function code($url)  {
        $qrCode = QrCode::create($url)
        // 内容编码
        ->setEncoding(new Encoding('UTF-8'))
        // 内容区域大小
        ->setSize(200)
        // 内容区域外边距
        ->setMargin(0);
        // 生成二维码数据对象
        $result = (new PngWriter)->write($qrCode);
        $dataUri = $result->getDataUri();
        return $dataUri;
    }

    //检查订单是否支付
    public function checkPay() : void {
        //订单待支付！
        $order_sn = $this->request->param('order_no');
        $order = Order::where(['order_no'=>$order_sn])->find();
        if(!$order){
            $this->error('错误');
        }
        if(intval($order->status) == 0){
            if(isOrderExpired($order['expire_at'])){
                $status = 203;
                $msg = '已过期订单';
            }else{
                $status = 202;
                $msg = '待支付订单';
            }
        }
        if(intval($order->status) == 1){
            $status = 1;
            $msg = '已支付';
        }
        $this->success($msg,null,$status);
    }


    //模拟支付成功
    public function paySuccess() : void {
        $order_no = $this->request->param('order_no');
        $order = Order::where('order_no', $order_no)->find();
        $pay_time = time();
         //进行订单状态变更等支付成功操作
         $order->status = PublicStatus::PUBLIC_STATUS_ONE;
         $order->pay_time = $pay_time;
         $order->save();
         //用户开通会员操作
         //1.获取用户信息
         $user = User::find($order->user_id);
         if (intval($order->recharge_type) == PublicStatus::PAY_STATUS_ONE) { //vip
          
            //开通vip操作
            $user_type = $order->vip_type;
            $recharge_time = date('Y-m-d', $pay_time);
            if (!empty($user->expiration_time)) {
                $syday = day_remaining_fun($user->expiration_time); //获取剩余天数
                $str = "vip续费";
            } else {
                $syday = 0;
                $str = "vip充值";
            }
            //获取开通的vip天数
            $vip_day = VipPrice::with(['day'])->find($order->vip_price_id);
      
            if (!$vip_day) {
                //如果订单状态异常直接退出
                $this->error("错误");
            }
            $count_day = $syday + intval(($vip_day['day']['day'])); //计算剩余天数 +累加
            $expiration_time = expiration_time_fun($pay_time, $count_day);
            UserMoneyLog::vipayAfter($this->auth->id,$order->pay_price,$recharge_time,$expiration_time,$user_type,$str,$order_no);

        }else{ //金币充值
            UserMoneyLog::payAfter($this->auth->id,$order->pay_price, '充值金币,金币额度:'.$order->pay_price,'takein',$order_no);
        }
        $this->success('ok');
    }
}